﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using WmsApp.Lookup;
using WmsApp.Service;
using WmsApp.UI;
using WmsApp.Window;
using WmsApp.WmsService;

namespace WmsApp.WindowControl
{
    public class PayApplyBillInvoiceController
    {
        private ControlType _controlType = ControlType.None;
        private PayApplyBillInvoiceWrap _wrap = null;
        private PayApplyBillInvoiceWrap Wrap {
            get { return _wrap; }
            set
            {
                this._wrap = value;
                if(value != null)
                {
                    CmdEnable(true);
                }
            }
        }
        private PayApplyBillCtl payApplyBillCtl = null;
        public PayApplyBillInvoiceController(PayApplyBillCtl ctl )
        {
            payApplyBillCtl = ctl;
            LookupBind.BindingLookUpEditProvider2(this.payApplyBillCtl.lookUpEditProvider3, this.payApplyBillCtl.textEditProviderName3
                ,this.payApplyBillCtl.textEditOpeningBank3,this.payApplyBillCtl.textEditBankAccount3);
            LookupBind.BindingLookUpEditSystemUser(this.payApplyBillCtl.lookUpEditChargeID3, this.payApplyBillCtl.textEditChargeName3, "ChargeName");
            LookupBind.BindingLookUpEditSystemUser(this.payApplyBillCtl.lookUpEditManagerID3, this.payApplyBillCtl.textEditManagerName3, "ManagerName");
            LookupBind.BindingLookUpEditSystemUser(this.payApplyBillCtl.lookUpEditOperatorID3, this.payApplyBillCtl.textEditOperatorName3, "OperatorName");
            LookupBind.BindingLookUpEditPayType(this.payApplyBillCtl.lookUpEditPayTypeCode3, this.payApplyBillCtl.textEditPayTypeName3);
            
            LookupBind.BindingLookUpEditIsAlive(this.payApplyBillCtl.gridView3,this.payApplyBillCtl.gridView3.Columns.ColumnByFieldName("ISVALID"));

            this.payApplyBillCtl.gridView3.CellValueChanged += GridView3CellValueChanged;

            CmdEnable(false);
        }

        private void CmdEnable(bool b)
        {
            this.payApplyBillCtl.CmdSave3.Enabled = b;
            this.payApplyBillCtl.CmdNewDtl3.Enabled = b;
            this.payApplyBillCtl.CmdInAffirm3.Enabled = b;
            this.payApplyBillCtl.CmdDelete.Enabled = b;
        }
        

        private void GridView3CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if(e.Column == payApplyBillCtl.gridView3.Columns.ColumnByFieldName("ISVALID")
                || e.Column == payApplyBillCtl.gridView3.Columns.ColumnByFieldName("Amount"))
            {
                decimal totalMoney = 0;
                foreach (var applyBillDtl in Wrap.FInvoiceBillList)
                {
                    totalMoney += applyBillDtl.AmountTax;
                }
                Wrap.FPayApplyBill.TotalAmount = totalMoney;
            }
        }

        public string CurrentPayApplyBillID
        {
            get { return this.Wrap.FPayApplyBill.PayApplyBillID; }
        }

        public string PayApplyState
        {
            get { return Wrap.FPayApplyBill.PayApplyState; }
        }

        public void NewOrLoadPayApplyBill(string inBillID)
        {
            var service = EntityServiceFactory.GetWrapService<PayApplyBillInvoiceWrap, PayApplyBillInvoiceWrapService>();
            Wrap = service.GetWrap(inBillID);
            if(Wrap == null)
            {
                NewPayApplyBill(inBillID);
            }
            else
            {
                LoadPayApplyBillID(inBillID);
            }
        }

        /// <summary>
        /// 编辑一个付款申请单
        /// </summary>
        /// <param name="payApplyBillID"></param>
        public void LoadPayApplyBillID(string payApplyBillID)
        {
            var service = EntityServiceFactory.GetWrapService<PayApplyBillInvoiceWrap, PayApplyBillInvoiceWrapService>();
            Wrap = service.GetWrap(payApplyBillID);
            _controlType = ControlType.Editing;
            this.DataBinding();
        }

        private void BindingDept()
        {
            var list = Factory.WmsServiceFactory.GetServiceClient().GetPayApplyBillDepts();
            this.payApplyBillCtl.comboBoxEditPayApplyDept3.Properties.Items.Clear();
            foreach (var dept in list)
            {
                this.payApplyBillCtl.comboBoxEditPayApplyDept3.Properties.Items.Add(dept);
            }
        }

        private void DataBinding()
        {
            BindingDept();
            //
            this.payApplyBillCtl.comboBoxEditPayApplyDept3.DataBindings.Clear();
            this.payApplyBillCtl.comboBoxEditPayApplyDept3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "PayApplyDept");
            //
            this.payApplyBillCtl.dateEditPayApplyDate3.DataBindings.Clear();
            this.payApplyBillCtl.dateEditPayApplyDate3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "PayApplyDate");
            //
            this.payApplyBillCtl.lookUpEditChargeID3.DataBindings.Clear();
            this.payApplyBillCtl.lookUpEditChargeID3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "ChargeID");
            //
            this.payApplyBillCtl.lookUpEditManagerID3.DataBindings.Clear();
            this.payApplyBillCtl.lookUpEditManagerID3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "ManagerID");
            //
            this.payApplyBillCtl.lookUpEditOperatorID3.DataBindings.Clear();
            this.payApplyBillCtl.lookUpEditOperatorID3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "OperatorID");
            //
            this.payApplyBillCtl.lookUpEditPayTypeCode3.DataBindings.Clear();
            this.payApplyBillCtl.lookUpEditPayTypeCode3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "PayTypeCode");
            //
            this.payApplyBillCtl.lookUpEditProvider3.DataBindings.Clear();
            this.payApplyBillCtl.lookUpEditProvider3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "ProviderCode");
            //
            this.payApplyBillCtl.textEditBankAccount3.DataBindings.Clear();
            this.payApplyBillCtl.textEditBankAccount3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "BankAccount");
            //
            this.payApplyBillCtl.textEditBillID3.DataBindings.Clear();
            this.payApplyBillCtl.textEditBillID3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "PayApplyBillID");
            //
            this.payApplyBillCtl.textEditChargeName3.DataBindings.Clear();
            this.payApplyBillCtl.textEditChargeName3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "ChargeName");
            //
            this.payApplyBillCtl.textEditIdx3.DataBindings.Clear();
            this.payApplyBillCtl.textEditIdx3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "Idx");
            //
            this.payApplyBillCtl.textEditManagerName3.DataBindings.Clear();
            this.payApplyBillCtl.textEditManagerName3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "ManagerName");
            //
            this.payApplyBillCtl.textEditOpeningBank3.DataBindings.Clear();
            this.payApplyBillCtl.textEditOpeningBank3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "OpeningBank");
            //
            this.payApplyBillCtl.textEditOperatorName3.DataBindings.Clear();
            this.payApplyBillCtl.textEditOperatorName3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "OperatorName");
            //
            this.payApplyBillCtl.textEditPayApplyStateDesc3.DataBindings.Clear();
            this.payApplyBillCtl.textEditPayApplyStateDesc3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "PayApplyStateDesc");
            //
            this.payApplyBillCtl.textEditPayTypeName3.DataBindings.Clear();
            this.payApplyBillCtl.textEditPayTypeName3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "PayTypeName");
            //
            this.payApplyBillCtl.textEditProviderName3.DataBindings.Clear();
            this.payApplyBillCtl.textEditProviderName3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "ProviderName");

            this.payApplyBillCtl.textEditTotalAmount3.EditValueChanged += (sender, e) =>
                                                                              {
                                                                                  try
                                                                                  {
                                                                                      this.payApplyBillCtl.textEditTotalAmountMax3.Text =
                                                                                      (new MoneyToChineseChanger(
                                                                                          decimal.Parse(this.payApplyBillCtl.textEditTotalAmount3.Text))).ToString();
                                                                                  }
                                                                                  catch (Exception)
                                                                                  {
                                                                                  }
                                                                              };
            //
            this.payApplyBillCtl.textEditTotalAmount3.DataBindings.Clear();
            this.payApplyBillCtl.textEditTotalAmount3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "TotalAmount");
            //
            this.payApplyBillCtl.memoEditArrivalNotice3.DataBindings.Clear();
            this.payApplyBillCtl.memoEditArrivalNotice3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "ArrivalNotice");
            //
            this.payApplyBillCtl.memoEditProjectBelong3.DataBindings.Clear();
            this.payApplyBillCtl.memoEditProjectBelong3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "ProjectBelong");
            //
            this.payApplyBillCtl.memoEditQualityFeedback3.DataBindings.Clear();
            this.payApplyBillCtl.memoEditQualityFeedback3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "QualityFeedback");

            this.payApplyBillCtl.gridControlEdit3.DataSource = Wrap.FInvoiceBillList;

            if(_wrap == null)
            {
                CmdEnable(false);
            }
            else
            {
                if(_wrap.FPayApplyBill.PayApplyState == Constant.BillStateDraft)
                {
                    CmdEnable(true);
                }
                else
                {
                    CmdEnable(false);
                }
            }
        }

        public void NewPayApplyBill(string inBillID)
        {
            if (Wrap != null)
            {
                if (Wrap.IsNeedSaved())
                {
                    if (DialogResult.OK == XtraMessageBox.Show(Wrap.FPayApplyBill.PayApplyBillID + "当前付款申请已修改，要保存吗？", "提问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                    {
                        SavePayApplyBill();
                    }
                }
            }

            //查询入库单，找到可以生成付款申请单的入库单

            string payApplyBillID = inBillID;
            if(String.IsNullOrEmpty(payApplyBillID))
            {
                var form = new FormInStoreBillSelector();
                form.ShowDialog();
                if(DialogResult.OK == form.DialogResult)
                {
                    payApplyBillID = form.FInStoreBill.BillID;
                }
                else
                {
                    return;
                }
            }

            Wrap = new PayApplyBillInvoiceWrap();
            Wrap.FPayApplyBill = PayApplyBill.CreatePayApplyBill(payApplyBillID);
            Wrap.FInvoiceBillList = new List<InvoiceBill>();
            _controlType = ControlType.New;
            this.DataBinding();
        }

        private bool Save()
        {
            if (Wrap != null && Wrap.FPayApplyBill != null)
            {
                //先校验出库单明细
                string msg = string.Empty;
                bool b = ValidatePayApplyBillDtl(out msg);
                if (!b)
                {
                    XtraMessageBox.Show(msg, "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return false;
                }

                IWrapService<PayApplyBillInvoiceWrap> wrapService =
                        EntityServiceFactory.GetWrapService<PayApplyBillInvoiceWrap, PayApplyBillInvoiceWrapService>();
                    wrapService.SaveWrap(Wrap);
              
                _controlType = ControlType.Saved;
            }
            return true;
        }

        private bool ValidatePayApplyBillDtl(out string msg)
        {
            msg = String.Empty;
            var query = from d in Wrap.FInvoiceBillList
                        select new
                        {
                            InvoiceNo = d.InvoiceNo
                        };
            if (Wrap.FInvoiceBillList.Count > query.Distinct().Count())
            {
                msg = "发票明细中含有重复的发票号码！";
                return false;
            }
            if (Wrap.FInvoiceBillList.Any(dtl => dtl.AmountTax == 0))
            {
                msg = "发票明细中的金额为0！";
                return false;
            }
            return true;
        }

        public void SavePayApplyBill()
        {
            if (Save())
            {
                XtraMessageBox.Show(Wrap.FPayApplyBill.PayApplyBillID + "保存成功！", "提示", MessageBoxButtons.OK,
                                    MessageBoxIcon.Information);
                this.LoadPayApplyBillID(Wrap.FPayApplyBill.PayApplyBillID);
            }
        }

        public void AffirmInStoreBill()
        {
            try
            {
                if (Save())
                {
                    Factory.WmsServiceFactory.GetServiceClient().AffirmPayApplyBill(Wrap.FPayApplyBill.PayApplyBillID);
                    _controlType = ControlType.Saved;
                    this.LoadPayApplyBillID(Wrap.FPayApplyBill.PayApplyBillID);
                }
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ShowException(ex);
            }
        }
    }
}
